<?php

namespace app\common\model;

use app\common\util\Tools;
use think\Model;

/**
 * Class Auth
 * @package app\common\model
 * 订单表
 */
class trOrder extends Model
{
    protected $pk = 'id';
    protected $resultSetType = 'collection'; //申明结果集是数据集对象（collection），查询结果才能用toArray()方法转为数组
    protected $name = "order"; //表名
    public $havingData = []; //存放已经获取的数据，减少数据库查询次数

    protected $type = [
        'create_time'  =>  'timestamp:Y-m-d H:i',
        'update_time'  =>  'timestamp:Y-m-d H:i',
        'pay_time'  =>  'timestamp:Y-m-d H:i',
    ];

    public function outletsDetail(){
        return $this->hasOne(trOrderOutletsDetail::class, "id", "order_id");
    }

    //转换字段
    public function transferField($data){
        if(!$data){
            return [];
        }
        $data = Tools::transferFields($data);
        if(isset($data[0])){
            if(isset($data[0]["userId"]))
                $userModel = new trUser();
            foreach ($data as $k => $item){
                if(!empty($item["userId"])){
                    if(isset($this->havingData[$item["userId"]])){
                        $data[$k]["userName"] = $this->havingData[$item["userId"]];
                    }else {
                        $data[$k]["userName"] = $this->havingData[$item["userId"]] = $userModel->getValue("nickname", ["id" => $item["userId"]]);
                    }
                }
                if(!empty($item["type"])){
                    $data[$k]["typeName"] =  $this->getAttrByType($item["type"]);
                }
                if(isset($item["status"])){
                    $data[$k]["statusText"] = $this->getAttrByStatus($item["status"]);
                }
                if(!empty($item["mobile"])){
                    $data[$k]["mobilePrefix"] = substr($item["mobile"], 0, -11);
                    $data[$k]["mobile"] = substr($item["mobile"], -11);
                }
                if (!empty($item["longLatFrom"])) {
                    $temp = explode(",", $item["longLatFrom"]);
                    $data[$k]["longitudeFrom"] = $temp[0];
                    $data[$k]["latitudeFrom"] = isset($temp[1]) ? $temp[1] : 0;
                }else{
                    $data[$k]["longitudeFrom"] = 0;
                    $data[$k]["latitudeFrom"] = 0;
                }
                if (!empty($item["longLatTo"])) {
                    $temp = explode(",", $item["longLatTo"]);
                    $data[$k]["longitudeTo"] = $temp[0];
                    $data[$k]["latitudeTo"] = isset($temp[1]) ? $temp[1] : 0;
                }else{
                    $data[$k]["longitudeTo"] = 0;
                    $data[$k]["latitudeTo"] = 0;
                }
                unset($data[$k]["longLatFrom"], $data[$k]["longLatTo"]);
            }
        }else{
            if(!empty($data["userId"])){
                $userModel = new trUser();
                if(isset($this->havingData[$data["userId"]])){
                    $data["userName"] = $this->havingData[$data["userId"]];
                }else {
                    $data["userName"] = $this->havingData[$data["userId"]] = $userModel->getValue("nickname", ["id" => $data["userId"]]);
                }
            }
            if(!empty($data["type"])){
                $data["typeName"] = $this->getAttrByType($data["type"]);
            }
            if(isset($data["status"])){
                $data["statusText"] = $this->getAttrByStatus($data["status"]);
            }
            if(!empty($data["mobile"])){
                $data["mobilePrefix"] = substr($data["mobile"], 0, -11);
                $data["mobile"] = substr($data["mobile"], -11);
            }
            if (!empty($data["longLatFrom"])) {
                $temp = explode(",", $data["longLatFrom"]);
                $data["longitudeFrom"] = $temp[0];
                $data["latitudeFrom"] = isset($temp[1]) ? $temp[1] : 0;
            }else{
                $data["longitudeFrom"] = 0;
                $data["latitudeFrom"] = 0;
            }
            if (!empty($data["longLatTo"])) {
                $temp = explode(",", $data["longLatTo"]);
                $data["longitudeTo"] = $temp[0];
                $data["latitudeTo"] = isset($temp[1]) ? $temp[1] : 0;
            }else{
                $data["longitudeTo"] = 0;
                $data["latitudeTo"] = 0;
            }
            unset($data["longLatFrom"], $data["longLatTo"]);
        }
        return $data;
    }

    public function getAttrByType($type)
    {
        //类型；1机场接送，2巴士路线，3专车接送，4包车线路
        switch ($type){
            case "1":
                return "机场接送";
                break;
            case "2":
                return "巴士路线";
                break;
            case "3":
                return "专车接送";
                break;
            case "4":
                return "包车线路";
                break;
            case "5":
                return "车辆租凭";
                break;
            default:
                return "其它";
                break;
        }
    }

    public function getAttrByStatus($status)
    {
        //订单状态：1待支付，2已支付，3已取消；4待分配；5已分配；6司机拒接；7司机已接单；8已完成；9已退款；10待退款；11部分退款
        switch ($status){
            case "1":
                return "待支付";
                break;
            case "2":
                return "已支付";
                break;
            case "3":
                return "已取消";
                break;
            case "4":
                return "待分配";
                break;
            case "5":
                return "已分配";
                break;
            case "6":
                return "司机拒接";
                break;
            case "7":
                return "司机已接单";
                break;
            case "8":
                return "已完成";
                break;
            case "9":
                return "已退款";
                break;
            case "10":
                return "待退款";
                break;
            case "11":
                return "部分退款";
                break;
            default:
                return "其它";
                break;
        }
    }

    //分页获取所有字段数据
    public function getList($field = '*', $filter = [], $page = 1, $limit = 10, $order = "create_time desc", $paginate = true){
        $db = self::where($filter)->field($field)->order($order);
        if($paginate){
            $data = $db->paginate(array('page' => $page, 'list_rows' => $limit));
            if($data){
                $data = $data->toArray();
                $data["data"] = $this->transferField($data["data"]);
                return $data;
            }
            return [];
        }else{
            if($page && $limit)
                $db->limit($page-1, $limit);
            $data = $db->select();
            $data = $this->transferField($data->toArray());
            return $data;
        }
    }

    //获取多字段数据
    public function getFields($field, $filter = [], $one = true, $toArray = true){
        if($one){
            $data = self::where($filter)->field($field)->find();
            return $data ? ($toArray ? $this->transferField($data->toArray()) : Tools::transferFields($data->getData())) : [];
        }else{
            $data = self::where($filter)->field($field)->select();
            return $data ? ($toArray ? $this->transferField($data->toArray()) : $data) : [];
        }
    }

    //获取订单编号
    public function getSn()
    {
        return date('YmdHis') . rand(100, 999);
    }

    //支付单号
    public function getPayNo(){
        return date('YmdHis') . rand(1000, 9999);
    }

    //根据条件获取数量
    public function getCount($filter = []){
        if(!empty($filter)){
            return self::where($filter)->count();
        }else{
            return self::count();
        }
    }

    //添加
    public function add($data, $getId=false){
        if(!$data)
            return true;
        $data["mall_id"] = request()->mallData["id"];
        $data["create_time"] = $data["update_time"] = time();
        if($getId){
            return self::insertGetId($data);
        }else{
            return self::insert($data);
        }
    }

    //更新
    public function doUpdate($data, $filter = []){
        if(!$data)
            return true;
        $data["update_time"] = time();
        return self::save($data, $filter);
    }

    //获取某字段的值
    public function getValue($field, $filter = []){
        if(!is_array($field)){
            return self::where($filter)->value($field);
        }
        return false;
    }

    //获取某字段的所有值
    public function getColumn($field, $filter = [], $key = ''){
        if(!is_array($field)){
            return self::where($filter)->column($field, $key);
        }
        return [];
    }

    //根据ID删除数据
    public function delById($id){
        if(is_array($id)){
            $result = self::where('id', 'in', $id)->delete();
        }else{
            $result = self::where('id', $id)->delete();
        }
        return $result;
    }
}